

const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const methodOverride = require('method-override');
const ejsMate = require('ejs-mate');


const htDiary = require('./model/htDiary');


mongoose.connect('mongodb://localhost:27017/dogs',{useNewUrlParser:true,useUnifiedTopology:true})
.then(()=>{
    console.log("open")
})
.catch(err =>{
    console.log("error");
    console.log(err)
})

app.engine('ejs', ejsMate);
app.set('view engine','ejs');
app.set('views', path.join(__dirname,'views'));


app.use(express.static(path.join(__dirname, 'views')));
app.use(express.urlencoded({ extended:true }));
app.use(methodOverride('_method'))


app.get('/htDiary',async (req,res) => {
    const htdiaries = await htDiary.find({});
    res.render('htDiary/index',{ htdiaries })
})

app.get('/htDiary/new', (req,res)=>{
    res.render('htDiary/new')
})


app.post('/htDiary',async (req,res)=>{
    const newDiary = new htDiary(req.body);
    await newDiary.save();
    res.render('htDiary/submit');
})

app.get('/htDiary/:id', async(req,res)=> {
    const { id } = req.params;
    const htdiary = await htDiary.findById(id);
    //console.log(htdiary);
     res.render('htDiary/show',{ htdiary });
})

app.get('/htDiary/:id/edit',async (req,res)=>{
    const { id } = req.params;
   // console.log({id});
    const htdiary = await htDiary.findById(id);
    res.render('htDiary/edit',{ htdiary });
})

app.put('/htDiary/:id',async (req,res) => {
    const { id } = req.params;
    const diary = await htDiary.findByIdAndUpdate(id,req.body,{runValidators:true, new:true});
    res.redirect(`/htDiary/${diary._id}`);
})

app.delete('/htDiary/:id',async (req,res) => {
    const { id } = req.params;
    const deleteDiary = await htDiary.findByIdAndDelete(id);
    res.render('htDiary/submit');
})




app.listen(3000, ()=>{
    console.log("app is listening!")
})